﻿# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.userDao  import UserDao
from com.zzh.validation.getMsgCode import MessageCode

import time
from . import app
from com.zzh.dao_v2.AuthTokenOperation import authTokenOperation
localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


CORS(app, supports_credentials=True)

@app.route('/queryUserById', methods=['POST'])
def queryUserById():

    if not request.json:
        abort(400)
    userId = request.json.get("userId")
    try:
        total_count, userCodeJSON= UserDao().queryUserById(userId)
        if total_count:
            return jsonify({"message": {"code": 1, "status": "queryUser OK"},"info":userCodeJSON})
        else:
            return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})

    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})

@app.route('/queryUserByCondition', methods=['POST'])
def queryUserByCondition():

    if not request.json:
        abort(400)
    try:
        page = request.json['page']
        pageIndex = page["pageIndex"]
        pageSize = page["pageSize"]
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})
    try:
        conditions = request.json['condition']
    except:
        return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
    try:
        multiSort = request.json['multiSort']
    except:
        return jsonify({"message": "未传入排序规则multiSort"})
    try:
        total_count, UserCodeJSON = UserDao().queryUserByCondition(pageIndex=pageIndex, pageSize=pageSize,conditions=conditions, multiSort=multiSort)
        if total_count:
                return jsonify({"message": {"code": 1, "status": "queryUser OK"},"total":total_count,"info":UserCodeJSON})
        else:
            return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})



@app.route('/insertUser', methods=['POST'])
def insertUser():

    if not request.json:
        abort(400)

    Info = {

        'userName': request.json.get('userName'),  #
        'userSalt': request.json.get('userSalt'),  #
        'userPassword': request.json.get('userPassword'),  #
        'userPhone': request.json.get('userPhone'),#
        'userEmail':request.json.get('userEmail'),
        'userAvatar': request.json.get('userAvatar'),  #
        'userNickName': request.json.get('userNickName'),#
        'userStatus':request.json.get('userStatus'),
        'userRegTime': request.json.get('userRegTime'),  #
        'userRegIp': request.remote_addr

    }
    if not Info:
        return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
    try:
        rs,user_json = UserDao().addUser(Info)
        if rs:
            return jsonify(
                {"massage": {"code": 1, "info": "addUser OK"},"info":user_json})  # 添加函数调用成功，返回添加的信息（不包括userRecharge的Id）
        else:
            return jsonify({"message": {"code": 0, "info": "addUser Error"}})  # 添加函数调用失败
    except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})




@app.route('/updateUser', methods=['POST'])
def updteUser():#

    try:
        userId = request.json['userId']
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 useId"}})
    try:
        oldInfo = UserDao().selectUser(userId)

    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
    Info = {
        'userId' : request.json['userId'],
        'userName': request.json.get('userName',oldInfo[1]),  #
        'userSalt': request.json.get('userSalt',oldInfo[2]),  #
        'userPassword': request.json.get('userPassword',oldInfo[3]),  #
        'userPhone': request.json.get('userPhone',oldInfo[4]),#
        'userEmail':request.json.get('userEmail',oldInfo[5]),
        'userAvatar': request.json.get('userAvatar',oldInfo[6]),  #
        'userNickName': request.json.get('userNickName',oldInfo[7]),#
        'userStatus':request.json.get('userStatus',oldInfo[8])

    }
    if not Info:
        return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
    try:
        rs = UserDao().updateUser(Info)
        if rs:
            return jsonify(
                {"info": Info, "massage": {"code": 1, "info": "updateUser OK"}})  # 添加函数调用成功，返回添加的信息
        else:
            return jsonify({"message": {"code": 0, "info": "updateUser Error"}})  # 添加函数调用失败
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})


@app.route('/deleteUser', methods=['DELETE'])  # 根据id数组删除zzh_user_Code表指定记录,传入格式为 "ids":[1,2,3,4]
def deleteUser():
    ids = request.json.get("ids")
    if not ids:
        return jsonify({"message":"请输入待删除的  id数组！"})
    try:
        rs = UserDao().deleteUser(ids)
        if rs:
            return jsonify({"message": {"code": 1, "info": "DeleteUser OK"}})
        else:
            return jsonify({"message": {"code": 0, "info": "DeleteUser Error"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})


@app.route('/isRegist', methods=['POST'])
def isRegist():
    """
    :return:
    """
    if not request.json:
        abort(400)
    # 首先判断手机号是否已被注册
    try:
        phone = request.json['userPhone']
    except:
        return jsonify({"message": {"code": 0, "info": "需传入参数userPhone！"}})

    res = UserDao().is_regist(phone)
    if res:
        # 若已被注册，返回-1
        return jsonify({"message": {"code": 0, "info": "该手机已被注册！"}})
    else:
        return jsonify({"message": {"code": 1, "info": "该手机未注册！"}})


@app.route('/registUser', methods=['POST'])
def registUser():
    if not request.json:
        abort(400)
    try:
        login_phone = request.json['userPhone']
        login_pwd = request.json['userPassword']
        code = request.json['code']
        userRegIP = request.remote_addr
        userRegTime = localTime
        invitedCode = request.json.get('invitedCode', None)  #注册成功后随机添加六位数字和字母组合的字符串到zzh_member中作为invited_code的值
    except:
        return jsonify({"message": {"code": 1, "info": "需要参数userPhone,userPassword,验证码code"}})

    res = MessageCode().verifyCode(login_phone, code)

    if res['code'] == 200:
        regist_info = {"login_phone": login_phone, "login_pwd": login_pwd, "invitedCode":invitedCode,"userRegIP":userRegIP, "userRegTime":userRegTime}
        res1, token = UserDao().regist_user(regist_info)
        if res1:
            return jsonify({"message": {"code": 1, "info": "success"}, "new_id": res1, "token": token[1]})
        else:
            return jsonify({"message": {"code": 0, "info": "Some error happen"}, "new_id": 0})
    else:
        return jsonify({"message": {"code": 0, "info": "验证码错误！"}})


# ------------获取短信验证码--------------
@app.route('/getVerifyCode', methods=['POST'])
def getVerifyCode():
    if not request.json:
        abort(400)
    try:
        phone = request.json['userPhone']
    except:
        return jsonify({"message": {"code": 0, "info": "需要参数userPhone"}})

    res = MessageCode().send(phone)
    if res['code'] == 200:
        return jsonify({"message": {"code": 1, "info": "验证码已发送！"}})
    else:
        return jsonify({"message": {"code": 0, "info": "验证码发送失败！"}})


# ---------检验短信验证码--------------
@app.route('/verifyCode', methods=['POST'])
def verifyCode():
    if not request.json:
        abort(400)
    try:
        phone = request.json['userPhone']
        code = request.json['code']
    except:
        return jsonify({"message": {"code": 0, "info": "需要参数userPhone,code！"}})

    res = MessageCode().verifyCode(phone, code)
    if res['code'] == 200:
        return jsonify({"message": {"code": 1, "info": "验证成功！"}})
    else:
        return jsonify({"message": {"code": 0, "info": "验证失败！"}})


# 用户登录

@app.route('/userLogin', methods=['POST'])
def userLogin():
        if not request.json:
            abort(400)
        try:
            phone = request.json['userPhone']
            password = request.json['userPassword']
        except:
            return jsonify({"message": {"code": 0, "info": "需要参数userPhone,userPassword！"}})

        code, userInfo = UserDao().user_login(phone, password)
        code2, token = authTokenOperation().generateToken(phone, password)

        if (code == 0 and code2 == 0):
            return jsonify({"message": {"code": 0, "info": "用户不存在！"}})
        elif (code == -1 and code2 == -1):
            return jsonify({"message": {"code": -1, "info": "密码错误！"}})
        elif ((code == 1 and code2 == 1)):
            return jsonify({"info": userInfo, "token": token, "message": {"code": 1, "info": "验证成功！"}})
        else:
            return jsonify({"mesage": "服务器异常信息"})



# 重置密码
@app.route('/resetPasswd', methods=['POST'])
def resetPasswd():
    if not request.json:
        abort(400)
    try:
        phone = request.json['userPhone']
        newpasswd = request.json['newPassword']
        code = request.json['code']
    except:
        return jsonify({"message": {"code": 0, "info": "需要参数userPhone,newPassword,验证码code！"}})

    verify = MessageCode().verifyCode(phone, code)
    if verify['code'] == 200:
        rs = UserDao().reset_passwd(newpasswd, phone)
        if rs:
            return jsonify({"message": {"code": 1, "info": "密码已重置！"}})
        else:
            return jsonify({"message": {"code": 0, "info": "Some error happened！"}})
    else:
        return jsonify({"message": {"code": 0, "info": "验证码错误！"}})


# -----------------密码修改----------------
@app.route('/updatePasswd', methods=['POST'])
def updatePasswd():
    if not request.json:
        abort(400)
    try:
        userId = request.json['userId']
        oldPwd = request.json['oldPwd']
        newPwd = request.json['newPwd']
    except:
        return jsonify({"message": {"code": 0, "info": "需要参数"}})

    rs = UserDao().update_passwd(userId, oldPwd, newPwd)
    if rs == 1:
        return jsonify({"message": {"code": 1, "info": "更新成功"}})
    elif rs == -1:
        return jsonify({"message": {"code": 0, "info": "原始密码错误"}})
    else:
        return jsonify({"message": {"code": 0, "info": "Some error happened"}})
